package com.gzzz.bean.impl;

import com.gzzz.bean.Input;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import static com.gzzz.utils.DBUtils.conn;
import static com.gzzz.utils.DBUtils.getConnection;

/**
 * className: DatabaseInput
 * Package : com.gzzz.bean.impl
 * Description:
 *
 * @Author yichen Li
 * @Create 2023/12/7 19:06
 * @Version 1.0
 */
public class DatabaseInput implements Input {
    @Override
    public InputStream read() {
        String selectSQL = "SELECT * FROM kwic WHERE id = ? ";
        int rid = 1;
        ResultSet rs = null;
        InputStream inputStream = null;
        //调用上面自己封装的getConnection方法连接数据库
        getConnection();
        //通过预处理对象处理sql语句
        PreparedStatement preSQL = null;
        try {
            preSQL = conn.prepareStatement(selectSQL);
            preSQL.setInt(1 , rid);
            //获取结果集对象
            rs= preSQL.executeQuery();
            //将rs转换为字符流
            while (rs.next()){
                byte[] bytes = rs.getString("lines").getBytes();//将字符串转换为字节数组
                inputStream = new ByteArrayInputStream(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库文件不存在！");
            return null;
        }
        //返回字符流
        return inputStream;
    }
}
